package cn.zgliang.blog.service.impl;

import cn.zgliang.blog.dao.TagRepository;
import cn.zgliang.blog.exception.NotFoundException;
import cn.zgliang.blog.po.Tag;
import cn.zgliang.blog.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/3/17 17:06
 * 描述：
 */
@Service
public class TagServiceImpl implements TagService {
    @Autowired
    private TagRepository typeRepository;
    @Transient
    @Override
    public Tag saveTag(Tag type) {
        return typeRepository.save(type);
    }


    @Transient
    @Override
    public Tag getTag(Long id) {
        return typeRepository.getOne(id);
    }
    @Transient
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Transient
    @Override
    public Tag updateTag(Long id, Tag type) {
        Tag one = typeRepository.getOne(id);
        if(one == null){
            throw new NotFoundException("不存在");
        }
        BeanUtils.copyProperties(type,one);
        return typeRepository.save(one);
    }
    @Transient
    @Override
    public void deleteTag(Long id) {
        typeRepository.deleteById(id);
    }

    @Override
    public Tag getTagByName(String name) {
        return typeRepository.findByName(name);
    }

    @Override
    public List<Tag> listTag() {
        return typeRepository.findAll();
    }

    @Override
    public List<Tag> listTag(String ids) {

        return typeRepository.findAllById(convertToList(ids));
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
        Pageable pageable = PageRequest.of(0, size, sort);
        return typeRepository.findTop(pageable);
    }

    private List<Long> convertToList(String data){
        List<Long>  list = new ArrayList<>();
        if(!"".equals(data) && data != null){
            String[] idarray = data.split(",");
            for (String s : idarray) {
                list.add(new Long(s));
            }
        }
        return list;
    }
}
